import httpx
import uvicorn
from fastapi import FastAPI, HTTPException, Header, Query, Response

# 创建 FastAPI 应用实例
app = FastAPI()

# 定义代理配置
SOCKS5H_PROXY = "socks5h://192.168.31.84:7891"

# 模拟更完整的浏览器头部
BROWSER_HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36",
    "Referer": "https://www.douyin.com/",
    "Accept": "image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8",
    "Accept-Encoding": "gzip, deflate, br",
    "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8"
}

# 创建两个 client：一个带代理，一个不带代理，并都添加完整的浏览器头部
client_with_proxy = httpx.AsyncClient(
    transport=httpx.AsyncHTTPTransport(proxy=SOCKS5H_PROXY),
    timeout=20,
    headers=BROWSER_HEADERS
)
client_no_proxy = httpx.AsyncClient(
    timeout=10,
    headers=BROWSER_HEADERS
)


@app.get("/google_search/image")
async def google_image_search(
    keyword: str = Query(..., description="要搜索的关键词"),
    page: int = Query(1, ge=1, description="结果页数，从1开始"),
    pagesize: int = Query(10, ge=1, le=10, description="每页结果数量，最大为10"),
    lang: str = Query("zh-CN", alias="lang", description="语言设置，例如: zh-CN (简体中文), en (英文)"),
    api_key: str = Header(..., alias="api-key", description="Google Custom Search API Key"),
    search_engine_id: str = Header(..., alias="search-engine-id", description="Google Custom Search Engine ID")
):
    """
    通过 Google Custom Search JSON API 进行图片搜索。
    这个请求会通过本地代理。
    """
    start_index = (page - 1) * pagesize + 1

    google_api_params = {
        "key": api_key,
        "cx": search_engine_id,
        "q": keyword,
        "searchType": "image",
        "num": pagesize,
        "start": start_index,
        "lr": lang
    }

    try:
        response = await client_with_proxy.get(
            "https://www.googleapis.com/customsearch/v1",
            params=google_api_params,
        )
        response.raise_for_status()
        return response.json()
    except httpx.HTTPStatusError as exc:
        raise HTTPException(
            status_code=exc.response.status_code,
            detail=f"请求 Google API 失败: {exc.response.text}"
        )
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"内部服务器错误: {str(e)}"
        )


@app.get("/image_proxy")
async def image_proxy(
    url: str = Query(..., description="要代理的图片链接")
):
    """
    代理图片链接，先尝试走代理，失败后再尝试不走代理。
    """
    try:
        # 第一次尝试：走代理
        response = await client_with_proxy.get(url, follow_redirects=True)
        response.raise_for_status()
        return Response(content=response.content, media_type=response.headers.get("Content-Type", "application/octet-stream"))
    except Exception as first_try_exc:
        print(f"第一次尝试（使用代理）失败: {first_try_exc}. 正在尝试第二次请求（不使用代理）...")

    try:
        # 第二次尝试：不走代理
        response = await client_no_proxy.get(url, follow_redirects=True)
        response.raise_for_status()
        return Response(content=response.content, media_type=response.headers.get("Content-Type", "application/octet-stream"))
    except Exception as second_try_exc:
        raise HTTPException(
            status_code=500,
            detail=f"代理图片请求失败: 两次尝试均失败。原始错误: {second_try_exc}"
        )


# 命令行运行入口
if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8902)